import {
  Box,
  Divider,
  Flex,
  ListItem,
  Text,
  UnorderedList,
  Button,
  Tooltip,
} from '@chakra-ui/react';
import { userInvoked } from 'store/actions';
import { useAppDispatch } from 'store/storeHooks';
import { useIsReadyToInvoke } from 'common/hooks/useIsReadyToInvoke';
import { clampSymmetrySteps } from 'features/parameters/store/generationSlice';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

export default function InvokeButton() {
  const dispatch = useAppDispatch();
  const { isReady, isProcessing } = useIsReadyToInvoke();

  const handleInvoke = useCallback(() => {
    dispatch(clampSymmetrySteps());
    dispatch(userInvoked('txt2img'));
  }, [dispatch]);

  const { t } = useTranslation();

  return (
    <Box style={{ flexGrow: 4 }} position="relative">
      <Tooltip
        label={isReady ? undefined : <InvokeButtonTooltipContent />}
        hasArrow={false}
      >
        <Button
          aria-label={t('parameters.invoke.invoke')}
          type="submit"
          data-progress={isProcessing}
          isDisabled={!isReady}
          onClick={handleInvoke}
          id="invoke-button"
          isLoading={isProcessing}
          loadingText={t('parameters.invoke.invoke')}
          sx={{
            w: 'full',
            flexGrow: 1,
            fontWeight: 700,
          }}
        >
          {t('parameters.invoke.invoke')}
        </Button>
      </Tooltip>
    </Box>
  );
}

export const InvokeButtonTooltipContent = memo(() => {
  const { isReady, reasons } = useIsReadyToInvoke();

  if (isReady) {
    return null;
  }
  return (
    <Flex flexDir="column" gap={1}>
      <Text fontWeight={600}>无法绘画</Text>
      {reasons.length > 0 && (
        <UnorderedList>
          {reasons.map((reason, i) => (
            <ListItem key={`${reason}.${i}`}>
              <Text fontWeight={400}>{reason}</Text>
            </ListItem>
          ))}
        </UnorderedList>
      )}
    </Flex>
  );
});

InvokeButtonTooltipContent.displayName = 'InvokeButtonTooltipContent';
